package com.horizon.im.common.codec;

import com.horizon.im.common.ProtocolInstant;
import com.horizon.im.common.bean.msg.ProtoMsg;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class ProtobufEncoder extends MessageToByteEncoder<ProtoMsg.Message> {
    public ProtobufEncoder() {
        super();
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, ProtoMsg.Message o, ByteBuf byteBuf) throws Exception {
        //魔术
        //版本
        byteBuf.writeShort(ProtocolInstant.MAGIC_CODE);
        byteBuf.writeShort(ProtocolInstant.VERSION_CODE);
        byte[] bytes =o.toByteArray();

        //读取消息长度
        int length = bytes.length;
        //先将消息长度写入
        byteBuf.writeInt(length);
        //再将消息写入
        byteBuf.writeBytes(bytes);
    }
}
